#include "plan.h"

CPlan::CPlan():m_Today(NULL)
			  ,m_LastDay(NULL)
			  ,m_BackTimes(0)
{

}

CPlan::~CPlan(){

}
void CPlan::initialize(){
	m_LastDay = new tm;
}

void CPlan::run(){
Times:
	if(m_BackTimes >= g_User.m_BackTimes)
		return;

AutoBackUp:
	if(!g_User.m_AutoBackUp)
		goto Scheduled;

System:
	int CPUsage = 0;
	DWORD IdleTime = 0;
	CPUsage = GetCPUsage();
	if(CPUsage >= g_User.m_UserCPUage)
		return;

	IdleTime = GetIdleTime();
	if(IdleTime < g_User.m_UserIdleTime)
		return;

Date:
	time(&m_Time);
	m_Today = localtime(&m_Time);
	if(m_LastDay->tm_yday != m_Today->tm_yday){
		m_LastDay = m_Today;
		m_BackTimes = 0;
		m_Begin = true;
		return;
	}

	if(m_LastDay->tm_year != m_Today->tm_year){
		m_LastDay = m_Today;
		m_BackTimes = 0;
		m_Begin = true;
	}
Scheduled:
	time(&m_Time);
	m_Today = localtime(&m_Time);

	if(g_User.m_WeekBackUp){
		if(m_Today->tm_wday != g_User.m_BackWDay)
			return;

		if(m_Today->tm_year < m_LastDay->tm_year)
			return;

		if(m_Today->tm_year > m_LastDay->tm_year)
			return;

		int j = 7;
		int i = ((m_Today->tm_yday) - (m_LastDay->tm_yday))/j;

		if(i < g_User.m_BackWeeks)
			return;

		if(i > g_User.m_BackWeeks){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}

		if(m_Today->tm_hour > m_LastDay->tm_hour){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}

		if(m_Today->tm_hour < m_LastDay->tm_hour)
			return;

		if(m_Today->tm_min < m_LastDay->tm_min)
			return;

		if(m_Today->tm_min >= m_LastDay->tm_min){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}

	}
	else{
		if(m_Today->tm_hour > m_LastDay->tm_hour){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}

		if(m_Today->tm_hour < m_LastDay->tm_hour){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}

		if(m_Today->tm_min < m_LastDay->tm_min){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}

		if(m_Today->tm_min >= m_LastDay->tm_min){
			m_LastDay = m_Today;
			m_Begin = true;
			return;
		}
	}
}

bool CPlan::getState(){
	return m_Begin;
}

void CPlan::setState(bool n_Begin){
	m_Begin = n_Begin;
}